package com.fingard.dsp.bank.directbank.icbc04;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.util.TransIDHelper;

import java.util.Date;

public class ICBC04Base extends DirectBase implements ITcpClient {
    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    private static TransIDHelper idHelper = new TransIDHelper(1, 9999);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    public String mac(String str) throws Exception {
        byte[] bytes = str.getBytes(getCharset());
        int len = bytes.length;
        byte mac[] = new byte[8];
        for (int i = 0; i < len; i += 8) {
            for (int j = 0; j < 8 && i + j < len; j++) {
                mac[j] = (byte) (mac[j] ^ bytes[i + j]);
            }
        }
        return new String(mac, getCharset());
    }

    public String leftFill(String sourceStr, int strLength, String fillChar) throws Exception {
        int length = 0;
        if (null != sourceStr) {
            length = sourceStr.getBytes(getCharset()).length;
        }
        for (int i = 0; i < strLength - length; i++) {
            if (sourceStr == null)
                sourceStr = fillChar;
            else
                sourceStr = fillChar + sourceStr;
        }
        return sourceStr;
    }

    protected String[] sendToBank(String p_reqStr) throws Exception {
        String[] retStr = new String[]{"", ""};
        WriteBankLogLn("2.提交银行的地址：" + bankFront.serverIP + ":" + bankFront.serverPort);
        WriteBankLogStep2(p_reqStr);

        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        TcpReceiver tmpReceiver = tmpClient.sendMessage(p_reqStr.getBytes(getCharset()));
        retStr[0] = tmpReceiver.connState;
        if (tmpReceiver.isCompleted) {
            retStr[1] = new String(tmpReceiver.recBytes, tmpReceiver.contentStartIndex, tmpReceiver.contentLength, getCharset());
            WriteBankLogStep3(retStr[1]);
        } else {
            retStr[1] = tmpReceiver.getConnMsg();
            WriteBankLogLn(retStr[1]);
        }
        return retStr;
    }

    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            if (p_receiver.readedLength > 0) {
                p_receiver.contentLength = p_receiver.readedLength;
                p_receiver.contentStartIndex = 0;
            }
        }
    }
}